import React, {useContext, useState} from 'react';
import {Button, Row, Col, Divider} from "antd";
import ThemeContext from "../../ThemeContext";
/**
 * 祖先组件
 * @returns {Element}
 * @constructor
 */
export const AncestorsComponents = function () {

    const [up, setUp] = useState(10);
    const [down, setDown] = useState(10);

    const change = type=>{
        switch (type) {
            case 'up':
                setUp(up+1);
                break;
            case 'down':
                setDown(down+1);
                break;
        }
    }

    return (
        <>
            <Row>
                <Col span={12} offset={6}>
                    <div>
                        <h2>
                            react是很棒的框架
                        </h2>
                        <Divider style={{marginBottom:'20px'}}/>
                        <ThemeContext.Provider value={{up,down,change,num:up+down}}>
                            <VoteFather/>
                        </ThemeContext.Provider>
                    </div>
                </Col>

            </Row>
        </>
    )

};

const VoteFather = ()=>{
    const {up,down} =  useContext(ThemeContext);
    return(
        <>
            <div>
                支持人数:{up}
            </div>
            <div>
                反对人数:{down}
            </div>
            <Divider style={{marginBottom:'20px'}}/>
            <VoteChildren/>
            <Divider/>
            <VoteOtherChildren/>
            <VoteClazzMain/>
        </>
    )
}


const VoteChildren  = ()=>{

    return (
        <>
            <ThemeContext.Consumer>
                {
                    context=>{
                        console.log(context,'context')
                        return <>
                            <Button type={'primary'} style={{marginRight:"20px"}} onClick={()=>context.change('up')}>支持</Button>
                            <Button type={'primary'} danger onClick={()=>context.change('down')}>反对</Button>
                            </>
                    }

                }
            </ThemeContext.Consumer>
        </>
    )
}

const VoteOtherChildren  = ()=>{

    const {change} = useContext(ThemeContext);

    return (
        <>
            <Button type={'primary'} style={{marginRight:"20px"}} onClick={()=>change('up')}>支持</Button>
            <Button type={'primary'} danger onClick={()=>change('down')}>反对</Button>
        </>
    )
}

class VoteClazzMain extends React.Component{
    //必须的,只有这一步后才会在this上挂载context,字段名得一样
    static contextType = ThemeContext;

    render(){
        const {num} = this.context;
        return (
            <>
             <h2>类组件接收ThemeContext</h2>
            <div>总数:{num}</div>
            </>
        )
    }
}